package ink.xiaobaibai.config;

import ink.xiaobaibai.filter.PageValidFilter;
import ink.xiaobaibai.rbac.AccessDecisionManagerImpl;
import ink.xiaobaibai.rbac.FilterInvocationSecurityMetadataSourceImpl;
import ink.xiaobaibai.rbac.RbacSecurityFilter2;
import ink.xiaobaibai.userDetails.UserNumberDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.header.Header;
import org.springframework.security.web.header.writers.StaticHeadersWriter;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

/**
 * @description: SpringSecurity的Web配置中心
 * @author: 小白白
 * @create: 2021-05-11
 **/

@Configuration
public class XbWebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserNumberDetailsServiceImpl userNumberDetailsService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private FilterInvocationSecurityMetadataSourceImpl filterInvocationSecurityMetadataSourceImpl;

    @Autowired
    private AccessDecisionManagerImpl accessDecisionManagerImpl;

//    @Autowired
//    private RbacSecurityFilter rbacSecurityFilter;

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
//                .anyRequest().authenticated()
                //所有资源都可以通过,有rbac护航
                .anyRequest().permitAll()
                .and()
                //CSRF禁用，因为不使用session
                .csrf().disable()
                //禁用session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .formLogin().disable() //禁用form登录
                //支持的跨域方法+请求头
                .headers().addHeaderWriter(new StaticHeadersWriter(Arrays.asList(
                new Header("Access-control-Allow-Origin", "*"),
                new Header("Access-Control-Expose-Headers", "Authorization"))))
                .and()
                //支持跨域
                .cors()
                .and()
                .addFilterAfter(new OptionsRequestFilter(), CorsFilter.class)
                //用户密码登录过滤器
                .apply(new MyUsernamePasswordAuthenticationConfig(this.userNumberDetailsService, this.stringRedisTemplate, this.passwordEncoder()))
                .and()
                //token验证拦截器
                .apply(new TokenAuthenticationConfig<>())
                .and()
                // FilterSecurityInterceptor为过滤器的最后一个链item
//        .addFilterBefore(new RbacSecurityFilter(filterInvocationSecurityMetadataSourceImpl,accessDecisionManagerImpl),FilterSecurityInterceptor.class)
                //自创改良版
                .addFilterBefore(new RbacSecurityFilter2(this.filterInvocationSecurityMetadataSourceImpl, this.accessDecisionManagerImpl), FilterSecurityInterceptor.class)
                .addFilterBefore(new PageValidFilter(), UsernamePasswordAuthenticationFilter.class)
        ;

    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        // 默认强度10+自定义盐 (我发现强度太大,需要算很久)
        return new BCryptPasswordEncoder(10);
    }

    /**
     * 另一种方法,试了好像没用
     */
//    @Autowired
//    private AccessDecisionManagerImpl accessDecisionManager;
//
//    @Autowired
//    private FilterInvocationSecurityMetadataSourceImpl metadataSource;

//    private class SecurityPostProcess implements ObjectPostProcessor<FilterSecurityInterceptor>{
//        @Override
//        public <O extends FilterSecurityInterceptor> O postProcess(O o) {
//            o.setSecurityMetadataSource(metadataSource);
//            o.setAccessDecisionManager(accessDecisionManager);
//            return o;
//        }
//    }

    /**
     * 内部类
     */
    private class OptionsRequestFilter extends OncePerRequestFilter {

        private final String OPTIONS = "OPTIONS";

        @Override
        protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
                throws ServletException, IOException {
            if (this.OPTIONS.equals(request.getMethod())) {
                response.setHeader("Access-Control-Allow-Methods", "*");
                response.setHeader("Access-Control-Allow-Headers", response.getHeader("Access-Control-Request-Headers"));
                return;
            }
            filterChain.doFilter(request, response);
        }

    }

    /**
     * 这个只对原生security生效,不对投票器生效
     * @return
     */
//    @Bean
//    public RoleHierarchy roleHierarchy(){
//        RoleHierarchyImpl roleHierarchy=new RoleHierarchyImpl();
//        /**
//         * 1.以/n结尾
//         * 2.大于号两边需要有空格
//         * 管理员-录入员-代理商-经销商
//         */
//        String hierarchy="admin > operator\n" +
//                "operator > agent\n" +
//                "agent > distributor\n";
//        roleHierarchy.setHierarchy(hierarchy);
//        return roleHierarchy;
//    }

}
